package com.eascs.admin.o2o.oper.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.common.utils.StringUtils;
import com.eascs.admin.o2o.badloan.service.ICancelService;
import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.admin.o2o.loan.entity.LoanApplyFileForm;
import com.eascs.admin.o2o.loan.entity.O2oLoanapplyEntity;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.admin.o2o.oper.entity.O2oOperUpEntity;
import com.eascs.admin.o2o.oper.entity.O2oOperationUploanlog;
import com.eascs.admin.o2o.oper.service.IO2oOperationUploanlogService;
import com.eascs.admin.o2o.oper.service.O2oOperUpService;
import com.eascs.admin.o2o.oper.vo.O2oOperUpVo;
import com.eascs.common.util.DateUtils;
import com.eascs.common.util.StringUtil;
import com.eascs.crm.common.entity.Acq;
import com.eascs.crm.common.service.AcqService;
import com.eascs.crm.common.vo.ModelResult;
import com.eascs.site.view.BaseRestResult;
import com.eascs.site.view.HtmlRestResult;
import com.eascs.site.view.ViewContext;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.web.url.UrlHelper;
import com.eascs.workflow.common.entity.sequence.SequenceEntity;
import com.eascs.workflow.common.entity.sys.ActOrgEntity;
import com.eascs.workflow.common.service.sequence.SequenceService;
import com.eascs.workflow.common.service.sys.SysOrgService;

@RestController
@RequestMapping("/roper_up")
public class O2oOperUpRestController {

	@Autowired
	O2oLoanapplyService o2oLoanapplyService;
	@Autowired
	O2oOperUpService operUpService;
	
	@Reference
	private SequenceService sequenceService;
	
	@Reference
	AcqService acqService;
	@Reference
	private SysOrgService sysOrgService;
	
	@Reference
	IO2oOperationUploanlogService iO2oOperationUploanlogService;
	

	@RequestMapping("/insert_view")
	public BaseRestResult<String> insertView(O2oOperUpVo operUpVo) {
		O2oLoanapplyEntity loanapplyEntity = o2oLoanapplyService.findById(operUpVo.getLoanapplyNo());
		ViewContext.put("loan", loanapplyEntity);
		return HtmlRestResult.popHtmlFragment("oper/oper_insert");
	}

	@RequestMapping("/insert_save")
	public BaseRestResult<String> insertSave(O2oOperUpVo operUpVo) {
		if (StringUtil.isBlank(operUpVo.getOperatorNo())) {
			return BaseRestResult.warn("未选中信贷经理，请选中！");
		}
		if (StringUtil.isBlank(operUpVo.getOpRemart())) {
			return BaseRestResult.warn("未填写备注，请填写备注！");
		}
		O2oLoanapplyEntity loanapplyEntity = o2oLoanapplyService.findById(operUpVo.getLoanapplyNo());

		if (!loanapplyEntity.getOperatorNo().equals(operUpVo.getOperatorNo())) {
			O2oOperUpEntity operUpEntity = new O2oOperUpEntity();
			operUpEntity.setLoanapplyNo(operUpVo.getLoanapplyNo());
			operUpEntity.setOpRemart(operUpVo.getOpRemart());
			operUpEntity.setOpTime(DateUtils.formateStandDateTime(new Date()));
			operUpEntity.setOpUserName(UserHolder.getUser().getCname());
			int i = operUpService.addOper(operUpEntity);
			if (i > 0) {
				loanapplyEntity.setOperatorNo(operUpVo.getOperatorNo());
				loanapplyEntity.setOperatorName(operUpVo.getOperatorName());
				o2oLoanapplyService.updateEntityById(loanapplyEntity);
			}
		} else {
			return BaseRestResult.warn("没有做任何修改，请修改信贷经理！");
		}
		return BaseRestResult.info("修改成功").andRefresh();
	}
	
	/**
	 * 修改申请贷款
	 * 
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/updateloan", method = RequestMethod.POST)
	public BaseRestResult<String> updateLoanApply(LoanApplyFileForm loanApplyFileEntity, String type, String upRemart) {
		O2oLoanapplyEntity entity = o2oLoanapplyService.findById(loanApplyFileEntity.getLoanapplyNo());
		if (StatusContexts.LOAN_TYPE_BP.equals(loanApplyFileEntity.getLoanType())||StatusContexts.LOAN_TYPE_BP_JX.equals(loanApplyFileEntity.getLoanType())||StatusContexts.LOAN_TYPE_SG.equals(loanApplyFileEntity.getLoanType())||StatusContexts.LOAN_TYPE_YC.equals(loanApplyFileEntity.getLoanType())||StatusContexts.LOAN_TYPE_SC.equals(loanApplyFileEntity.getLoanType())) {
			if (StringUtil.isEmpty(loanApplyFileEntity.getPartnerId())) {
				return BaseRestResult.warn("请选择渠道");
			} else {
				entity.setPartnerId(loanApplyFileEntity.getPartnerId());
				ModelResult<Acq> model = acqService.selectAcq(loanApplyFileEntity.getPartnerId());
				if (model.isSuccess()) {
					Acq acq = model.getModel();
					entity.setPartnerCode(acq.getAcqCode());
					entity.setPartnerName(acq.getAcqName());
				} else {
//					o2oLoanapplyEntity.setPartnerName(addloanapplyForm.getPartnerName());
					return BaseRestResult.warn("渠道保存异常，没有找到此渠道！");
				}
			}
		}
		if (StatusContexts.LOAN_TYPE_BK.equals(loanApplyFileEntity.getLoanType())) {
			if (StringUtil.isBlank(loanApplyFileEntity.getCustomerSdNo())) {
				return BaseRestResult.warn("请选客户名称：");
			} else {
				entity.setCustomerCode(loanApplyFileEntity.getCustomerCode());
				entity.setCustomeRname(loanApplyFileEntity.getCustomerName());
				entity.setCustomerNo(loanApplyFileEntity.getCustomerSdNo());
			}
		}
		if (loanApplyFileEntity.getLoanaMount()==null) {
			return BaseRestResult.warn("申请金额不能为空");
		}

		BigDecimal loanAmout = new BigDecimal(1000000.00);
		if (loanApplyFileEntity.getLoanaMount().compareTo(loanAmout) == 1) {
			return BaseRestResult.warn("申请金额不能超过100万");
		} else if (loanApplyFileEntity.getLoanaMount().compareTo(new BigDecimal(10000.00)) == -1) {
			return BaseRestResult.warn("申请金额不能小于1万");
		}
		User user = UserHolder.getUser();
		entity.setEndRo(user.getNo());
		ActOrgEntity actOrgEntity = null;
		if ("ZY".equals(loanApplyFileEntity.getOperationModel())) {
			loanApplyFileEntity.setLtd(loanApplyFileEntity.getLtd1());
			actOrgEntity = sysOrgService.getOrgByUnitNo(loanApplyFileEntity.getLtd());
		} else {
			actOrgEntity = sysOrgService.getOrgByUnitNo(loanApplyFileEntity.getLtd());
		}
		if (entity != null && entity.getBillCode() == null) {
			entity.setBillCode(buildCode(actOrgEntity.getUnitCode(), loanApplyFileEntity.getLoanType()));
		}
		Date date = new Date();
		entity.setLoanaMount(loanApplyFileEntity.getLoanaMount());
		entity.setLoanapplyNo(loanApplyFileEntity.getLoanapplyNo());
		entity.setEndDate(date);
		entity.setLoanType(loanApplyFileEntity.getLoanType());
		entity.setLtd(loanApplyFileEntity.getLtd());
		entity.setLtdCode(actOrgEntity.getUnitCode());
		entity.setLtdName(actOrgEntity.getOrgName());
		if (loanApplyFileEntity.getLoanTerm() != null) {
			entity.setLoanTerm(Integer.parseInt(loanApplyFileEntity.getLoanTerm()));
		} else {
			entity.setLoanTerm(0);
		}
		entity.setOperatorNo(loanApplyFileEntity.getOperatorNo());
		entity.setOperatorName(loanApplyFileEntity.getOperatorName());
		entity.setRepayMentway(loanApplyFileEntity.getRepayMentway());
		entity.setGuarAnteeWay(loanApplyFileEntity.getGuarAnteeWay());
		entity.setReferrerNo(loanApplyFileEntity.getReferrerNo());
		entity.setReferrerName(loanApplyFileEntity.getReferrerName());
		entity.setCommiceRecommend(loanApplyFileEntity.getCommiceRecommend());
		entity.setOperationModel(loanApplyFileEntity.getOperationModel());
		if (!StringUtil.isEmpty(loanApplyFileEntity.getRemark()))
			entity.setRemark(loanApplyFileEntity.getRemark().trim());
		o2oLoanapplyService.updateFormApplyLoan(entity);
		if (StringUtil.isNotBlank(type) && "detail".equals(type)) {
			O2oOperationUploanlog uploanlog = new O2oOperationUploanlog();
			uploanlog.setBillCode(entity.getBillCode());
			uploanlog.setLoanapplyNo(entity.getLoanapplyNo());
			uploanlog.setUpTime(date);
			uploanlog.setUpRemart(upRemart);
			uploanlog.setUpUserName(user.getCname());
			uploanlog.setUpUserNo(user.getNo());
			iO2oOperationUploanlogService.insert(uploanlog);
		}
		return BaseRestResult.info("保存成功").andRedirect(UrlHelper.build("/detail?loanapplyNo=" + entity.getLoanapplyNo()));
	}
	
	/**
	 * 生成贷款编号
	 * 
	 * @param code
	 * @param type
	 * @return
	 */
	public String buildCode(String code, String type) {
		String bill = StringUtils.getFourBitYearMonth(new Date());
		String prefix = code + "-" + type + "-" + bill;
		String flag = sequenceService.getSeq(SequenceEntity.O2O_LOAN_NO, StatusContexts.O2O_SEQUENCE_LENGTH, prefix);
		if (flag == null) {
			throw new RuntimeException();
		}
		return flag;
	}
	
	@Reference
	ICancelService iCancelService;
	
	@RequestMapping("/test")
	public BaseRestResult<String> test(){
		O2oOperUpEntity entity = operUpService.queryOperUpByLoanapplyNo("");
		System.err.println(entity);
		System.err.println(iCancelService.findByLoanapplyId(""));
		return BaseRestResult.warn("123");
	}
}
